﻿<script lang="ts" setup name="sysoutstockorder">
import { ref, reactive, onMounted } from "vue";
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from "element-plus";
import { downloadStreamFile } from "/@/utils/download";
import { useSysoutstockorderApi } from '/@/api/OutWarehou/sysoutstockorder';
import editDialog from '/@/views/OutWarehou/sysoutstockorder/component/editDialog.vue'
import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import ImportData from "/@/components/table/importData.vue";

const sysoutstockorderApi = useSysoutstockorderApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const state = reactive({
  exportLoading: false,
  tableLoading: false,
  stores: {},
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime', // 默认的排序字段
    order: 'descending', // 排序方向
    descStr: 'descending', // 降序排序的关键字符
  },
  tableData: [],
});

// 页面加载时
onMounted(async () => {
});

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  state.tableParams = Object.assign(state.tableParams, params);
  const result = await sysoutstockorderApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then(res => res.data.result);
  state.tableParams.total = result?.total;
  state.tableData = result?.items ?? [];
  state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 删除
const delSysoutstockorder = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await sysoutstockorderApi.delete({ id: row.id });
    handleQuery();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

// 批量删除
const batchDelSysoutstockorder = () => {
  ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await sysoutstockorderApi.batchDelete(state.selectData.map(u => ({ id: u.id }) )).then(res => {
      ElMessage.success(`成功批量删除${res.data.result}条记录`);
      handleQuery();
    });
  }).catch(() => {});
};

// 导出数据
const exportSysoutstockorderCommand = async (command: string) => {
  try {
    state.exportLoading = true;
    if (command === 'select') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map(u => u.id) });
      await sysoutstockorderApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'current') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams);
      await sysoutstockorderApi.exportData(params).then(res => downloadStreamFile(res));
    } else if (command === 'all') {
      const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
      await sysoutstockorderApi.exportData(params).then(res => downloadStreamFile(res));
    }
  } finally {
    state.exportLoading = false;
  }
}

// 预测对话框状态
const predictDialogVisible = ref(false);
const predictLoading = ref(false);
const predictResult = ref<any>(null);

// 预测功能
const handlePredict = async () => {
  try {
    // 检查是否有数据
    if (!state.tableData || state.tableData.length === 0) {
      ElMessage.warning('当前没有数据，无法进行预测！请先查询数据。');
      return;
    }
    
    predictLoading.value = true;
    predictDialogVisible.value = true;
    
    // 获取当前表格数据，提取出库日期和出库数量
    const historyData = state.tableData.map((item: any) => ({
      date: item.outDate,
      quantity: item.outQuantity || 0,
      documentStatus: item.documentStatus || 0
    }));
    
    ElMessage.info('正在调用预测服务，请稍候...');
    
    // 调用预测API
    const response = await fetch('http://localhost:5000/predict', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        documentStatus: historyData.length > 0 ? historyData[0].documentStatus : 0
      })
    });
    
    if (!response.ok) {
      throw new Error('预测API调用失败');
    }
    
    const result = await response.json();
    
    // 处理预测结果
    predictResult.value = {
      predictedValues: result.documentStatus || [],
      lowerBounds: result.documentStatus_LB || [],
      upperBounds: result.documentStatus_UB || [],
      historicalData: historyData
    };
    
    ElMessage.success('预测完成！');
    
  } catch (error: any) {
    console.error('预测失败:', error);
    
    // 更详细的错误提示
    let errorMessage = '预测失败: ';
    if (error.message.includes('Failed to fetch')) {
      errorMessage = '无法连接到预测服务！请确认：\n1. MLModel1_WebApi1 项目已启动\n2. 服务运行在 http://localhost:5000\n3. 检查防火墙设置';
    } else {
      errorMessage += error.message || '未知错误';
    }
    
    ElMessageBox.alert(errorMessage, '预测服务错误', {
      type: 'error',
      confirmButtonText: '我知道了'
    });
    
    predictDialogVisible.value = false;
  } finally {
    predictLoading.value = false;
  }
};

// 关闭预测对话框
const closePredictDialog = () => {
  predictDialogVisible.value = false;
  predictResult.value = null;
};

handleQuery();
</script>
<template>
  <div class="sysoutstockorder-container" v-loading="state.exportLoading">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }"> 
      <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库单号">
              <el-input v-model="state.tableQueryParams.code" clearable placeholder="请输入出库单号"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库类型">
              <el-input v-model="state.tableQueryParams.outType" clearable placeholder="请输入出库类型"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="单据状态">
              <g-sys-dict v-model="state.tableQueryParams.documentStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择单据状态" clearable filterable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库日期">
              <el-date-picker type="daterange" v-model="state.tableQueryParams.outDateRange"  value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="仓库名称">
              <el-input v-model="state.tableQueryParams.warehouseName" clearable placeholder="请输入仓库名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="关联单号">
              <el-input v-model="state.tableQueryParams.relatedCode" clearable placeholder="请输入关联单号"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="客户名称">
              <el-input v-model="state.tableQueryParams.customerName" clearable placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="联系人">
              <el-input v-model="state.tableQueryParams.contactPerson" clearable placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="联系方式">
              <el-input v-model="state.tableQueryParams.contactMethod" clearable placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库货品">
              <el-input v-model="state.tableQueryParams.goodsName" clearable placeholder="请输入出库货品"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库数量">
              <el-input-number v-model="state.tableQueryParams.outQuantity"  clearable placeholder="请输入出库数量"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="出库金额">
              <el-input-number v-model="state.tableQueryParams.outbouAmount"  clearable placeholder="请输入出库金额"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="备注">
              <el-input v-model="state.tableQueryParams.remark" clearable placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
            <el-form-item label="软删除时间">
              <el-date-picker type="daterange" v-model="state.tableQueryParams.deleteTimeRange"  value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item >
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'sysoutstockorder:page'" v-reclick="1000"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => state.tableQueryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="() => state.showAdvanceQueryUI = true" v-if="!state.showAdvanceQueryUI" style="margin-left:5px;"> 高级查询 </el-button>
                <el-button icon="ele-ZoomOut" @click="() => state.showAdvanceQueryUI = false" v-if="state.showAdvanceQueryUI" style="margin-left:5px;"> 隐藏 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete" @click="batchDelSysoutstockorder" :disabled="state.selectData.length == 0" v-auth="'sysoutstockorder:batchDelete'"> 删除 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增系统出库单表')" v-auth="'sysoutstockorder:add'"> 新增 </el-button>
                <el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportSysoutstockorderCommand">
                  <el-button type="primary" style="margin-left:5px;" icon="ele-FolderOpened" v-reclick="20000" v-auth="'sysoutstockorder:export'"> 导出 </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
                      <el-dropdown-item command="current">导出本页</el-dropdown-item>
                      <el-dropdown-item command="all">导出全部</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-button type="warning" style="margin-left:5px;" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'sysoutstockorder:import'"> 导入 </el-button>
                <el-button type="info" style="margin-left:5px;" icon="ele-TrendCharts" @click="handlePredict"> 预测 </el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" @selection-change="(val: any[]) => { state.selectData = val; }" style="width: 100%" v-loading="state.tableLoading" tooltip-effect="light" row-key="id" @sort-change="sortChange" border>
        <el-table-column type="selection" width="40" align="center" v-if="auth('sysoutstockorder:batchDelete') || auth('sysoutstockorder:export')" />
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop='code' label='出库单号' show-overflow-tooltip />
        <el-table-column prop='outType' label='出库类型' show-overflow-tooltip />
        <el-table-column prop='documentStatus' label='状态' show-overflow-tooltip>
          <template #default="scope">
            <g-sys-dict v-model="scope.row.documentStatus" code="DocumentStatusEnum" />
          </template>
        </el-table-column>
        <el-table-column prop='outDate' label='出库日期' show-overflow-tooltip />
        <el-table-column prop='relatedCode' label='关联单号' show-overflow-tooltip />
        <el-table-column prop='customerName' label='客户名称' show-overflow-tooltip />
        <el-table-column prop='contactPerson' label='联系人' show-overflow-tooltip />
        <el-table-column prop='contactMethod' label='联系方式' show-overflow-tooltip />
        <el-table-column prop='goodsName' label='出库货品' show-overflow-tooltip />
        <el-table-column prop='outQuantity' label='出库数量' show-overflow-tooltip />
        <el-table-column label='出库金额' show-overflow-tooltip>
          <template #default="scope">
            {{ (scope.row.outbouAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('sysoutstockorder:update') || auth('sysoutstockorder:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑系统出库单表')" v-auth="'sysoutstockorder:update'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text type="primary" @click="delSysoutstockorder(scope.row)" v-auth="'sysoutstockorder:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
              v-model:currentPage="state.tableParams.page"
              v-model:page-size="state.tableParams.pageSize"
              @size-change="(val: any) => handleQuery({ pageSize: val })"
              @current-change="(val: any) => handleQuery({ page: val })"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100, 200, 500]"
              :total="state.tableParams.total"
              size="small"
              background />
      <ImportData ref="importDataRef" :import="sysoutstockorderApi.importData" :download="sysoutstockorderApi.downloadTemplate" v-auth="'sysoutstockorder:import'" @refresh="handleQuery"/>
      <printDialog ref="printDialogRef" :title="'打印系统出库单表'" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" @reloadTable="handleQuery" />
    </el-card>
    
    <!-- 预测结果对话框 -->
    <el-dialog
      v-model="predictDialogVisible"
      title="出库数量预测结果"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-loading="predictLoading" style="min-height: 300px;">
        <div v-if="predictResult && !predictLoading">
          <el-descriptions title="预测信息" :column="2" border>
            <el-descriptions-item label="历史数据条数">
              {{ predictResult.historicalData.length }}
            </el-descriptions-item>
            <el-descriptions-item label="预测周期">
              {{ predictResult.predictedValues.length }} 期
            </el-descriptions-item>
          </el-descriptions>
          
          <el-divider />
          
          <h4>预测结果详情</h4>
          <el-table :data="predictResult.predictedValues.map((val: number, index: number) => ({
            period: index + 1,
            predicted: val.toFixed(2),
            lowerBound: predictResult.lowerBounds[index]?.toFixed(2) || '-',
            upperBound: predictResult.upperBounds[index]?.toFixed(2) || '-'
          }))" border style="margin-top: 10px;">
            <el-table-column prop="period" label="预测周期" width="100" align="center" />
            <el-table-column prop="predicted" label="预测值" align="center" />
            <el-table-column prop="lowerBound" label="置信区间下限" align="center" />
            <el-table-column prop="upperBound" label="置信区间上限" align="center" />
          </el-table>
          
          <el-divider />
          
          <h4>历史数据</h4>
          <el-table :data="predictResult.historicalData.slice(0, 10)" border style="margin-top: 10px;" max-height="300">
            <el-table-column prop="date" label="出库日期" width="180" />
            <el-table-column prop="quantity" label="出库数量" align="center" />
            <el-table-column prop="documentStatus" label="单据状态" align="center" />
          </el-table>
          <div v-if="predictResult.historicalData.length > 10" style="text-align: center; margin-top: 10px; color: #999;">
            仅显示前10条历史数据，共 {{ predictResult.historicalData.length }} 条
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="closePredictDialog">关闭</el-button>
        <el-button type="primary" @click="closePredictDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
:deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>